<?php
namespace control;
/*
*报废申请单类
*/

class scrappedOrderClass extends adIndexClass
{
    private const table = 'scrapped_order';
    private const tableMx = 'scrapped_order_detail';
    private const page = 'scrappedOrder';
    private const title = '报废申请单';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "报废申请单号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'machiningSendOrder'  => [
                        'name'  => '生产派工单号',
                        'width' => 150,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 100,
                    ],
                    'teamNo'          => [
                        'name'  => '班次',
                        'width' => 150,
                    ],
                    'team'          => [
                        'name'  => '班组',
                        'width' => 200,
                    ],
                    'subject'          => [
                        'name'  => '存货类型',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '产品名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'planNum'          => [
                        'name'  => '计划产量',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '报废数量',
                        'width' => 100,
                    ],
                    'warehouse'          => [
                        'name'  => '仓库',
                        'width' => 150,
                    ],
                    'stid'          => [
                        'name'  => '申请人',
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $array = [
            [
                [
                    "状态" => checkbox(array('name' => 'state', 'value' => $this->stateOption, 'checked' => ['草稿', '审核中'])),
                ],
                [
                    "报废申请单号" => text(array("name" => "orderNo")),
                    "生产派工单号"   => text(array('name' => 'machiningOrderNo')),
                    '班组' => selectMultiple(array("name" => "teamId", "table" => "team",'where'=>"coid = '".self::$coid."'",   'sqlField' => 'name', 'sqlId' => 'id', "class" => "width200")),
                ],
                [
                    "工序" => selectMultiple(array("name" => "processId", "table" => "process",'where'=>"coid = '".self::$coid."'",   'sqlField' => 'name', 'sqlId' => 'id', "class" => "width200")),
                    "产品名称" => text(array('name' => 'materialName')),
                    "班次" => select(array('name' => 'teamType', 'option' => explode('，', para('teamType')))),
                ],
                [
                    "班次日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'datetime', 'range' => '~'])),
                ]
            ]
        ];
        if ($this->power(self::page, "seeAll")) {
            $array[0][3]['申请人'] = selectMultiple(array("name" => "stid", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid', "class" => "width200"));
        }
        //生成查询表单
        $html = $this->tableShow($array,1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*行政人事-出差记录-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }



    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "teamType" => $this->post('teamType'),
            "processId" => $this->post('processId'),
            "teamId" => $this->post('teamId'),
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //初始化
        $and = "";
        $mAnd = '';
        if ($this->post('machiningOrderNo')) {
            $and .= " and sendId in (select id from machining_send_order where  coid = '" . self::$coid . "' and orderNo like '%" . $this->post('machiningOrderNo') . "%')";
        }
        if ($this->post('materialName')) {
            $mAnd = " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and  materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'teamNo');
        }
        if ($this->post('state')) {
            //单据日期
            $and .= " and state in ('" . implode("','", $this->post('state')) . "')";
        }
        //如果没有查看所有员工请假记录的权限
        if (!$this->power(self::page, "seeAll")) {
            $and .= $this->seeSelf(self::page);
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";

        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $machiningSendOrder = query('machining_send_order', "id = '$array[sendId]'");
            $material = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'machiningSendOrder':
                        $row[] = $machiningSendOrder['orderNo'];
                        break;
                    case 'line':
                        $line = query('product_line', "id = '$machiningSendOrder[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'process':
                        $process = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'teamNo':
                        $row[] = $array['teamNo'] . ' ' . $array['teamType'];
                        break;
                    case 'team':
                        $team = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'subject':
                    case 'code':
                    case 'name':
                    case 'model':
                        $row[] = $material[$key];
                        break;
                    case 'unit':
                        $row[] = $machiningSendOrder['unit'];
                        break;
                    case 'planNum':
                        $row[] = self::lostZero($machiningSendOrder['num'],'numPrecision');
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $planQuery = find([
            'table'  => 'machining_send_order',
            'single' => " id in (select sendId from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'planNum'        => self::lostZero($planQuery['num'], 'numPrecision'),
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id') ?: self::getId();
        $clockRuleTr = '';
        $info = query(self::table, " id = '" . $id . "' ");
        $process = query('process', "id = '$info[processId]'");
        $defectOption = $process['id'] ? explode('，', $process['defectType']) : [];
        $result = find(array('table' => self::tableMx, 'where' => " orderId = '$info[id]' order by list asc"));
        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span class='btn-borderless' onclick='addRow(this)'>添加</span>";
                } else {
                    $button = "<span class='btn-borderless' onclick='decRow(this)'>删除</span>";
                }
                $input = hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    select(array('name' => 'problem[]', 'title' => '请选择', 'value' => $array['problem'], 'option' => $defectOption)) .
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'title' => '数量', 'value' => self::lostZero($array['num'],'numPrecision')));
                $clockRuleTr .= <<<efo
<div class='item_row flex-box'>{$input}{$button}</div>
efo;
            }
        } else {
            $button = "<span class='btn-borderless' onclick='addRow(this)'>添加</span>";
            $input = hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                select(array('name' => 'problem[]', 'title' => '请选择', 'option' => $defectOption)) .
                text(array('name' => 'num[]', 'title' => '数量', 'other' => self::digitalFiltering('numPrecision'), 'value' => ''));
            $clockRuleTr .= <<<efo
<div class='item_row flex-box'>{$input}{$button}</div>
efo;
        }
        if ($info['sourceTable'] == 'machining_card_detail') {
            $machining_card_detail = query('machining_card_detail', "id = '$info[sendId]'");
            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
        }else{
            $sourceOrder = query('machining_send_order', "id = '$info[sendId]'");
        }
        $materialName = $sourceOrder['id'] ? materialClass::getName($sourceOrder['materialId']) : '';
        $planNum = $sourceOrder['id'] ? (self::lostZero($sourceOrder['num'],'numPrecision') . $sourceOrder['unit']) : '';
        $line = query('product_line', "id = '$sourceOrder[lineId]'");
        $lineName = $line['workshop'] . '-' . $line['name'];
        $teamType = explode('，', para('teamType'));
        //表单
        $html = $this->layerEdit([
            "table" => [
                array(
                    must . "生产派工单/生产流转卡：" => hidden(array('name' => 'sendId', 'value' => $info['sendId'])) .
                        "<span id='machiningOrder'>{$sourceOrder['orderNo']}</span>
                        <span class='del-row-button' style='margin-left: 5px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','addMaterial',{})\">选择</span>",
                    "生产线：" => "<span id='line'>{$lineName}</span>",
                ),
                array(
                    must . "工序：" => "<div id='process'>" . $process['name'] . "</div>" . hidden(array('name' => 'processId', 'value' => $process['id'])),
                    "物料：" => "<span id='material'>{$materialName}</span>",
                ),
                array(
                    '计划数量：' => "<span id='machiningNum'>{$planNum}</span>",
                    must . "班次：" => text(array("name" => "teamNo", "laydate" => array(), "value" => $info['id'] ? $info['teamNo'] : $this->date)) .
                        select(array('name' => 'teamType', 'option' => $teamType, 'title' => '请选择', 'value' => $info['teamType'] ?: $teamType[0])),
                ),
                array(
                    must . "班组：" => "<div id='team'>".selectMultiple(array("name" => "teamId", 'value' => $info['teamId'], "title" => "班组", "table" => "team", 'where' => " state ='启用' and coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id'))."</div>",
                    must . "报废数量：" => text(array("name" => "scrapNum", 'other' => self::digitalFiltering('numPrecision'), "value" => self::lostZero($info['num'],'numPrecision'))),
                ),
                array(
                    "批次：" => text(array("name" => "batchNo", "value" => $info['batchNo'])),
                    must . "入库仓库：" => selectMultiple(array('name' => 'warehouseId', 'value' => $info['warehouseId'], 'title' => '请选择', 'sqlId' => 'id', 'table' => 'warehouse', 'where' => "coid = '" . self::$coid . "' and state = '启用' order by time", 'sqlField' => 'name'))
                ),
                array(
                    "报废原因：" => "<div class='row-li'>" . $clockRuleTr . "</div>",
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 500, "html" => $html));
    }

    public function js(): string
    {
        return <<<efo
<style>
#team{width: 100%;}
.row-li{width: 100%;}
.row-li .item_row{gap: 4px;}
.row-li .btn-borderless {width: 100px;}
</style>
<script>
 //添加一行
         function addRow(){
             let processId = $("[name='processId']").val();
             if (!processId){
                 msg('请先选择工序','error');
             }else{
                 $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{processId:processId},function (res){
                     $(".row-li").append(res.data);
                 },'json');
             }
         }
          //选择生产产品
    function addMaterial(){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                    $('#scrappedOrderAddMaterial').hide();
                    $("#machiningNum").html(res.planNum+res.unit);
                    $("#process").empty().append(res.process);
                    $("[name='processId']").val(res.processId);
                    $("#machiningOrder").html(res.orderNo);
                    $("#line").html(res.lineName);
                    $("#material").html(res.materialName);
                    $("[name='sendId']").val(res.id);
                    $(".row-li").find("[name='problem[]']").empty().append(res.problem);
                    $("#team").empty().append(res.teamId);
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;
    }

    /**
     * 添加一行
     *
     * @return bool|string
     */
    public function addRow()
    {
        $process = query('process', "id = '" . $this->post('processId') . "'");
        $defectOption = $process['id'] ? explode('，', $process['defectType']) : [];
        $json['data'] = "<div class='item_row flex-box'>" .
                            hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                            select(array('name' => 'problem[]', 'title' => '请选择', 'value' => '', 'option' => $defectOption)) .
                            text(array('name' => 'num[]', 'title' => '数量', 'value' => '')) .
                            "<span class='btn-borderless' onclick='decRow(this)'>删除</span>
                        </div>";
        return json_encode($json, 320);
    }

    /*编辑*/
    public function editEdit()
    {

        $id = $this->post('id') ?: self::getId();
        $problemArr = $this->post('problem') ?: [];
        $numArr = $this->post('num') ?: [];
        $mxIdArr = $this->post('mxId') ?: [];
        //赋值
        $field = array(
            "batchNo" => $this->post('batchNo'),
            "warehouseId" => $this->post('warehouseId'),
            "sendId" => $this->post('sendId'),//备注
            'teamNo' => $this->post('teamNo'),
            "teamType" => $this->post('teamType'),
            "teamId" => $this->post('teamId'),
            "num" => $this->post('scrapNum')?self::formattingFigure($this->post('scrapNum'),'numPrecision'):'',
        );
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
        if ($isProductCard) {
            $machining_card_detail = query('machining_card_detail', "id = '$field[sendId]'");
            $field['sendId'] = $machining_card_detail['id'];
            $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
            $field['processId'] = $machining_card_detail['processId'];
            $field['sourceTable'] = 'machining_card_detail';
        }else{
            $sourceOrder = query('machining_send_order', "id = '$field[sendId]'");
            $field['sendId'] = $sourceOrder['id'];
            $field['processId'] = $sourceOrder['processId'];
            $field['sourceTable'] = 'machining_send_order';
        }
        $field['materialId'] = $sourceOrder['materialId'];
        $field['lineId'] = $sourceOrder['lineId'];
        $field['unit'] = $sourceOrder['unit'];
        $annotation = [
            "sendId" => '来源单据',
            'teamNo' => '班次',
            "teamType" => '班次',
            "teamId" => '班组',
            "num" => '报废数量',
            "processId" => '工序',
            "materialId" => '物料ID',
            "lineId" => '生产线',
            "unit" => '单位',
        ];
        $rules = [
            "sendId" => 'required',
            'teamNo' => 'required',
            "teamType" => 'required',
            "teamId" => 'required',
            "num" => 'required|numeric',
            'processId' => 'required',
            "materialId" => 'required',
            "lineId" => 'required',
            "unit" => 'required',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['id'] && $info['state'] != '草稿') {
            $json['warn'] = '此申请单不是草稿状态，不能编辑';
        }elseif($field['num'] < floatval(array_sum($numArr))){
            $json['warn'] = '明细的报废数量之和不能超过总的报废数量';
        } else {
            $this->startTrans();
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'BFSQ' . date('Ymd',strtotime($field['teamNo'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, array("id" => $id, 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            $newIdArr = [];
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $mxId) {
                    if (!empty($problemArr[$k])) {
                        $newIdArr[] = $mxId;
                        $mx = query(self::tableMx, "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            $warn = static::update(array(
                                'table' => self::tableMx,
                                'field' => array(
                                    'problem' => $problemArr[$k],
                                    'num' => $numArr[$k],
                                ),
                                'where' => "id = '$mx[id]'",
                            ));
                        } else {
                            $warn = static::insert(array(
                                'table' => self::tableMx,
                                'field' => array(
                                    'id' => $mxId,
                                    'coid' => self::$coid,
                                    'orderId' => $id,
                                    'problem' => $problemArr[$k],
                                    'num' => $numArr[$k],
                                ),
                            ));
                        }
                        if (!in_array($warn, array("新增成功", "更新成功"))) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
            }

            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $newIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '报废申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'finishFunc',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分入库','已入库')")) == 0) {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'cancelFunc',
                            'data' => ['id' => $info['id']]
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    public function cancelFunc($data){
        //删除入库单
        delete(array('table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$data[id]' and coid = '" . self::$coid . "')"));
        delete(array('table' => 'inventory', 'where' => "sourceId = '$data[id]'"));
    }
    /**
     * 审批通过执行
     * @param $data
     * @return bool|string
     */
    public function finishFunc($data): bool|string
    {
        $info = query(self::table, "id = '$data[id]'");
        $id = self::getId();
        $field = [
            'id' => $id,
            'type' => '报废入库',
            'coid' => self::$coid,
            'sourceTable' => self::table,
            'sourceId' => $info['id'],
            'sourceNo' => $info['orderNo'],
            'warehouseId' => $info['warehouseId'],
            'targetId' => $info['lineId'],
            'classify' => 1,
            'state' => '待入库',
            'workFlow' => '已质检',
            'stid' => self::$stid,
        ];
        $userNo = codeTemplateClass::generateCode('inStock',[
            'prefix' => 'KCRK' . date('Ymd'),
            'table' => 'inventory',
            'field' => 'orderNo',
            'where' => " and coid = '" . self::$coid . "'",
        ],$field);
        $field['orderNo'] = $userNo;
        $warn = static::insert(array(
            'table' => 'inventory',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增入库单失败";
        }
        $warn = static::insert(array(
            'table' => 'inventory_detail',
            'field' => [
                'id' => self::getId(),
                'coid' => self::$coid,
                'sourceTable' => self::tableMx,
                'sourceId' => $info['id'],
                'materialId' => $info['materialId'],
                'warehouseId' => $info['warehouseId'],
                'unit' => $info['unit'],
                'orderId' => $id,
                'orderNum' => $info['num'],
                'rate' => 0,
                'price' => 0,
            ]
        ));
        if ($warn != '新增成功') {
            return "新增入库单明细失败";
        }
        return true;
    }

    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];

                //审核按钮
                $button = array_merge($button, $this->auditButton($info));
                if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "edit",
                        "post" => ["id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
                if ($info['sourceTable'] =='machining_card_detail'){
                    $machining_card_detail = query('machining_card_detail', "id = '$info[sendId]'");
                    $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
                    $machining_order_mx = query('machining_order_mx',"id = '$sourceOrder[sourceMxId]'");
                }else{
                    $sourceOrder = query($info['sourceTable'], "id = '$info[sendId]'");
                    $machining_order_mx =  query('machining_order_mx',"id = '$sourceOrder[machiningOrderMxId]'");
                }
                $machining_order = query('machining_order',"id = '$machining_order_mx[orderId]'");
                $line = query('product_line', "id = '$info[lineId]'");
                $process = query('process', "id = '$info[processId]'");
                $team = query('team', "id = '$info[teamId]'");
                $mxStr = find(array('table' => self::tableMx, "single" => "orderId = '$info[id]' group by orderId", 'field' => "group_concat(concat(any_value(problem),',',any_value(num))) as str"));
                $warehouse = query('warehouse', "id = '$info[warehouseId]'");
                //生成表单
                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    "基本信息" => array(
                        array(
                            "报废申请单号" => $info['orderNo'],
                            '生产线' => $line['workshop'] . '-' . $line['name'],
                            "派工单号/生产流转卡单号" => $sourceOrder['orderNo'],
                            "工序" => $process['name'],
                        ),
                        array(
                            "物料" => materialClass::getName($info['materialId']),
                            "生产数量" => self::lostZero($machining_order_mx['num'],'numPrecision') . $info['unit'],
                            "计划开始时间" => $machining_order['startDate'],
                            "计划下线时间" => $machining_order['endDate'],
                        ),
                        array(
                            "备注" => pre($machining_order['text']),
                        ),
                    ),
                    '报废信息' => array(
                        array(
                            "班次" => $info['teamNo'] . '-' . $info['teamType'],
                            "班组" => $team['name'],
                            "报废数量" => self::lostZero($info['num'],'numPrecision') . $info['unit'],
                            "批次" => $info['batchNo'],
                        ),
                        array(
                            "报废原因" => $mxStr['str'] ?? '',
                            "入库仓库" => $warehouse['name'],
                        ),
                        array(
                            "备注" => pre($info['text']),
                        ),
                    ),
                    '系统信息' => array(
                        array(
                            "创建人" => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                            "状态" => $info['state']
                        ),
                    ),
                    '流程' => array(
                        array(
                            auditClass::auditRecord(self::table, $info['id'])
                        )
                    ),
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "删除失败：不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     *选择生产产品
     *
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
            //生成生产流转卡
            $title = '生产流转卡编号';
        } else {
            $title = '生产派工单号';
        }
        $html =
            text(array("name" => "orderNo", "title" =>$title)) .
            text(array('name' => 'code', 'title' => '产品编码')) .
            text(array('name' => 'materialName', 'title' => '产品名称')) .
            text(array('name' => 'model', 'title' => '产品型号'));
        $button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
            $json['html'] = $this->machiningCardSearch();
        } else {
            $and = " and machiningOrderId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
            $mAnd = '';
            $like = [
                'orderNo'=>$this->post('orderNo')
            ];
            $equal = [
                'coid' => self::$coid,
                'classify' => '生产派工',
                'state' => '已确认',
            ];

            if ($this->post('code')) {
                $mAnd .= " and code like '%" . $this->post('code') . "%'";
            }
            if ($this->post('materialName')) {
                $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
            }
            if ($this->post('model')) {
                $mAnd .= " and model like '%" . $this->post('model') . "%'";
            }
            if ($mAnd) {
                $and .= " and materialId in (select id from material where 1=1 {$mAnd})";
            }
            $where = search(["like" => $like, "=" => $equal]) . $and;
            $page = $this->page([
                "table" => "machining_send_order",
                "where" => $where,
                'pageNum' => 50,
                "order" => "orderNo desc",
            ]);
            //获取表头
            $tr[] = ['', '生产派工单号', '单据日期', '生产线', '产品编码', '产品名称', '产品型号', '工序'];
            //获取记录
            foreach ($page['array'] as $array) {
                $material = query('material', "id = '$array[materialId]'");
                $line = query('product_line', "id = '$array[lineId]'");
                $process = query('process', "id = '$array[processId]'");
                $tr[] = array(
                    "<input name='mxId' value='$array[id]' type='radio'>",
                    $array['orderNo'],
                    date('Y-m-d', strtotime($array['time'])),
                    $line['workshop'] . '-' . $line['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $process['name'],
                );
            }
            $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        }

        return json_encode($json, 320);
    }
    /**
     * 生产流转卡
     */
    public function machiningCardSearch()
    {
        $and = " and a.sourceId not in (select id from machining_order where coid = '" . self::$coid . "' and isClose = 1)";
        $like = [
            'a.orderNo' => $this->post('orderNo'),
            'c.code' => $this->post('code'),
            'c.name' => $this->post('materialName'),
            'c.model' => $this->post('model'),
        ];
        $equal = [
            'a.coid' => self::$coid,
        ];
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "machining_card as a join machining_card_detail as b on a.id = b.orderId join material as c on c.id = a.materialId",
            'field' => "a.*,b.processId,b.id as mxId,c.name,c.code,c.model",
            "where" => $where,
            'pageNum' => 50,
            "order" => "a.orderNo desc,b.list asc",
        ]);
        //获取表头
        $tr[] = ['', '生产流转卡单号','单据日期', '生产线', '工序', '产品编码', '产品名称', '产品型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $line = query('product_line', "id = '$array[lineId]'");
            $process = query('process', "id = '$array[processId]'");
            $tr[] = array(
                "<input name='mxId' value='$array[mxId]' type='radio'>",
                $array['orderNo'],
                $array['recordDate'],
                $line['workshop'] . '-' . $line['name'],
                $process['name'],
                $array['code'],
                $array['name'],
                $array['model'],
            );
        }
        return $page['hint'] . "<form name='mxForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $id = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '请选择生产计划单';
        } else {
            if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
                $machining_card_detail = query('machining_card_detail', "id = '$id'");
                $sourceOrder = query('machining_card', "id = '$machining_card_detail[orderId]'");
                $routingDetail = query('routing_detail', "id = '$machining_card_detail[routingMxId]'");
                $process = query('process', "id = '$machining_card_detail[processId]'");
            }else{
                $sourceOrder = query('machining_send_order', "id = '$id'");
                $routingDetail = query('routing_detail', "id = '$sourceOrder[routingMxId]'");
                $process = query('process', "id = '$sourceOrder[processId]'");
            }
            $line = query('product_line', "id = '$sourceOrder[lineId]'");
            $lineName = $line['workshop'] . '-' . $line['name'];
            $json['process'] = $process['name'];
            $json['processId'] = $process['id'];
            $json['valuationType'] = $routingDetail['valuationType'];
            $json['planNum'] = self::lostZero($sourceOrder['num'],'numPrecision');
            $json['unit'] = $sourceOrder['unit'];
            $json['materialName'] = materialClass::getName($sourceOrder['materialId']);
            $json['id'] = $id;
            $json['orderNo'] = $sourceOrder['orderNo'];
            $json['lineName'] = $lineName;
            $json['teamId'] = selectMultiple(array("name" => "teamId", 'value' =>$sourceOrder['teamId']??'', "title" => "班组", "table" => "team", 'where' => " state ='启用' and coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id'));
            $json['problem'] = option(array('option' => $process['defectType'] ? explode('，', $process['defectType']) : [], 'title' => '请选择'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

}
